package com.tzxx.spider.service;

import lombok.extern.slf4j.Slf4j;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tzxx.spider.dao.ArticleLinkMapper;
import com.tzxx.spider.domain.ArticleLink;

/**
 * @author Created by tzxx
 * @since : 2019/7/19.
 */
@Slf4j
@Service("articleLinkService")
@Transactional
public class ArticleLinkService {

    private SqlSessionTemplate sqlSessionTemplate;
    @Resource
    private ArticleLinkMapper articleLinkMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void insertList2Redis(List<ArticleLink> articleLinkList) {
        redisTemplate.convertAndSend("links",articleLinkList);
    }

    public void insertList2Mysql(List<ArticleLink> articleLinkList) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        ArticleLinkMapper mapper = session.getMapper(ArticleLinkMapper.class);
        try {
            for (int i = 0; i < articleLinkList.size(); i++) {
                mapper.insert(articleLinkList.get(i));
                if (i % 1000 == 999 || i == articleLinkList.size() - 1) {
                    session.commit();
                    session.clearCache();
                }
            }
        } catch (Exception e) {
            log.error("error:{}", e.getMessage());
            session.rollback();
        } finally {
            session.close();
        }
    }

    public void insert(ArticleLink articleLink) {
        articleLinkMapper.insert(articleLink);
    }

    public void delete(long id) {
        articleLinkMapper.deleteById(id);
    }

    public ArticleLink findById(long id) {
        return articleLinkMapper.selectById(id);
    }

}
